<?php
/**
 * 模型类
 */
class Model{
    //保存静态连接信息
    static private $link = NULL;
    //表名
    private $table;
    //保存sql所需的一些初始化信息比如字段field，where..
    private $opt = array();


    /**
     * 自动执行初始化
     */
    public function __construct($table){
        //初始化表名
        $this->table = C('DB_PREFIX') . $table;
        //连接数据库
        $this->_connect();
        // 初始化opt信息
        $this->_opt();
    }

    /**
     * [_opt 初始化opt信息]
     * @return [type] [description]
     */
    private function _opt(){
        $this->opt = array(
            'field' =>  '*',
            'where' =>  '',
            'group' =>  '',
            'having'=>  '',
            'order' =>  '',
            'limit' =>  ''
            );
    }

    /**
     * 连接数据库
     */
    private function _connect(){
        if(!is_null(self::$link)) return;
        //mysqli连接
        $mysqli = @new Mysqli(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'),C('DB_NAME'));
        //判断是否连接有误
        if($mysqli->connect_errno) halt('数据库连接失败或者选择库失败，请检查配置项! ):');
        //指定字符集
        $mysqli->query('SET NAMES ' . C('DB_CHARSET'));
        self::$link = $mysqli;
    }

    /**
     * [find 取一条数据]
     * @return [type] [description]
     */
    public function find(){
        $data = $this->all();
        //取得当前单元
        return current($data);
    }

    /**
     * [limit 截取]
     * @param  [type] $limit [description]
     * @return [type]        [description]
     */
    public function limit($limit){
        $this->opt['limit'] = " LIMIT " . $limit;
        return $this;
    }

    /**
     * [order 排序]
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    public function order($order){
        $this->opt['order'] = " ORDER BY " . $order;
        return $this;
    }
    /**
     * [where where条件]
     * @param  [type] $where [description]
     * @return [type]        [description]
     */
    public function where($where){
        $this->opt['where'] = " WHERE " . $where;
        return $this;
    }
    /**
     * [field 指定字段]
     * @param  [type] $field [description]
     * @return [type]        [description]
     */
    public function field($field){
        $this->opt['field'] = $field;
        return $this;
    }
    /**
     * [all 查询所有数据]
     * @return [type] [description]
     */
    public function all(){
        // 1.group 
        // 2.order
        // 3.having
        // 4.where
        // 5.select
        // 6.limit

        // 5-4-1-3-2-6

        //组合sql语句
        $sql = "SELECT " . $this->opt['field'] . " FROM " . $this->table . $this->opt['where'] . $this->opt['group'] . $this->opt['having'] . $this->opt['order'] . $this->opt['limit'];
        
        return $this->query($sql);
    }
    /**
     * 负责查询有结果集的操作
     */
    public function query($sql){
        //用mysqli查询query
        $result = self::$link->query($sql);
        //如果执行错误
        $this->_error($sql);

        $rows = array();
        while($row = $result->fetch_assoc()){
            $rows[] = $row;
        }
        //释放结果集
        $result->free_result();
        return $rows;
    }

    /**
     * [add 添加数据]
     */
    public function add($data = NULL){
        //如果不传递$data按照$_POST来
        if(is_null($data)) $data = $_POST;
        //组合键名
        $var = '';
        $value = '';
        foreach ($data as $k => $v) {
            $var .= adds_html($k) . ',';
            $value .= '"' . adds_html($v) . '",';
        }
        $var = rtrim($var,',');
        $value = rtrim($value,',');
        //组合sql
        $sql = "INSERT INTO " . $this->table . "({$var}) VALUES ({$value})";
        //执行增加
        return $this->exec($sql);   
    }
    /**
     * [delete 删除]
     * @return [type] [description]
     */
    public function delete(){
        //where不能为空
        if(empty($this->opt['where'])) halt('删除语句必须有where条件！');

        $sql = "DELETE FROM " . $this->table . $this->opt['where'];
        //执行删除
        return $this->exec($sql);

    }
    /**
     * [update 修改]
     * @return [type] [description]
     */
    public function update($data = NULL){
        if(empty($this->opt['where'])) halt('修改语句必须有where条件！');
        if(is_null($data)) $data = $_POST;
        // p($data);die;
        // Array
        // (
        //     [name] => 新闻
        //     [pinyin] => xinwen
        // )
        $var = '';
        foreach ($data as $k => $v) {
            $var .= $k . '="' . $v . '",';
        }
        $var = rtrim($var,',');

        // $sql = "UPDATE stu SET name='新闻',pinyin='xinwen' WHERE nid>1";
        
        $sql = "UPDATE " . $this->table  . " SET " . $var . $this->opt['where'];
        
        return $this->exec($sql);
    }
    
    /**
     * 负责执行无结果集的操作
     */
    public function exec($sql){
        self::$link->query($sql);

        // 如果有错，提示错误提示方法
        $this->_error($sql);
        //返回自增id或者受影响条数
        return self::$link->insert_id ? self::$link->insert_id : self::$link->affected_rows;
    }

    /**
     * [_error 错误提示方法]
     * @param  [type] $sql [description]
     * @return [type]      [description]
     */
    private function _error($sql){
        if(self::$link->errno){
             halt("SQL:<span style='color:red'>{$sql}</span><br/>ERROR:" . self::$link->error);
        }
    }
}































